<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-过磅单`"
		width="1500px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:fullscreen="false"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn()"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail'" label-width="100px" :show-message="false">
			<div ref="box1">
				<div class="flex-between-center margin-bottom-4">
					<el-tag type="primary" effect="plain">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<div class="flex-end-center">
						<jk-button v-if="pageType === 'detail'" :has-permission="getPermission([`${prefix}:export`])" :disabled="ruleForm.auditState === 0" class="margin-5-0 item-gap" type="warning" @click="onReportBtn">导出</jk-button>
					</div>
				</div>
				<jk-card class="margin-bottom-10">
					<el-row>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="存货编码" prop="productCode">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.productCode }}</span>
								<remoteSearchCodeInput
									v-else
									placeholder="存货编码"
									only-key="productCode"
									query-name="productCode"
									:form-data="ruleForm"
									@on-select="onSelectProductCodeChange"
								></remoteSearchCodeInput>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="原批" prop="primaryBatchCode">
								<span class="read-only-2">{{ ruleForm.primaryBatchCode }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="厂批" prop="workshopBatchCode">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.workshopBatchCode }}</span>
								<div v-else>
									<remote-search-product-input
										:is-valid-date="true"
										placeholder="厂批"
										only-key="workshopBatchId"
										query-name="workshopBatchCode"
										:form-data="ruleForm"
										@on-select="onSelectBatchChange"
									></remote-search-product-input>
								</div>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
			</div>
			<div ref="box2" style="display: flex" class="margin-bottom-4">
				<el-tag type="primary" effect="plain">
					<span class="el-icon-document item-gap"></span>
					<span>过磅明细</span>
				</el-tag>
				<jk-button v-if="pageType === 'edit'" size="mini" style="margin-left: 5px" type="primary" @click="addProductList">添加明细</jk-button>
				<jk-button v-if="pageType !== 'detail'" size="mini" :has-permission="getPermission([`${prefix}:button`])" style="margin-left: 5px" type="warning" @click="addTareState">皮重输入</jk-button>
			</div>
			<jk-table
				ref="jkTable"
				show-footer
				:span-method="mergeColMethod"
				:footer-method="footerMethod"
				border
				:data="ruleForm.itemList"
				:height="dialogTableHeight - 150"
			>
				<vxe-column title="操作" align="left" :width="70">
					<template #header>
						<span slot="reference">操作</span>
					</template>
					<template slot-scope="scope">
						<div slot="reference" class="drag-info-icon" style="color: #2d8cf0;font-size: 13px;">
							<jk-button icon="el-icon-minus" :disabled="ruleForm.itemList.length === 1 || pageType === 'detail'" size="mini" @click="ruleForm.itemList.length !== 1 ? ruleForm.itemList.splice(scope.rowIndex, 1) : ''"></jk-button>
						</div>
					</template>
				</vxe-column>
				<vxe-column title="到货日期" align="left" field="belongDate" :min-width="133">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.belongDate }}</span>
						<jk-date-picker v-else v-model="scope.row.belongDate" size="mini" placeholder="到货日期" />
					</template>
				</vxe-column>
				<!--				<vxe-column title="存货编码" align="left" field="productCode" :min-width="140">-->
				<!--					<template slot-scope="scope">-->
				<!--						<span v-if="pageType === 'detail'">{{ scope.row.productCode }}</span>-->
				<!--						<remoteSearchCodeInput-->
				<!--							v-else-->
				<!--							placeholder="存货编码"-->
				<!--							size="mini"-->
				<!--							only-key="productCode"-->
				<!--							query-name="productCode"-->
				<!--							:form-data="scope.row"-->
				<!--							@on-select="onSelectProductCodeChange(scope.row, $event, scope.rowIndex)"-->
				<!--						></remoteSearchCodeInput>-->
				<!--					</template>-->
				<!--				</vxe-column>-->
				<vxe-column title="车号" align="left" field="carCode" :min-width="80">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.carCode }}</span>
						<el-input v-else v-model="scope.row.carCode" size="mini" placeholder="车号" />
					</template>
				</vxe-column>
				<!--				<vxe-column title="原批" align="left" field="primaryBatchCode" :min-width="130">-->
				<!--					<template slot-scope="scope">-->
				<!--						<span v-if="pageType === 'detail'">{{ scope.row.primaryBatchCode }}</span>-->
				<!--						<el-input v-else v-model="scope.row.primaryBatchCode" disabled size="mini" placeholder="原批" />-->
				<!--					</template>-->
				<!--				</vxe-column>-->
				<vxe-column title="单个皮重(kg)" align="right" field="oneTare" :min-width="80">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.oneTare }}</span>
						<jk-number-input v-else v-model="scope.row.oneTare" :disabled="tareState === 0" size="mini" placeholder="单个皮重(kg)" @input="blurNetWeight(scope.row, scope.row.oneTare, scope.rowIndex)" />
					</template>
				</vxe-column>
				<vxe-column title="总皮重(kg)" align="right" field="tare" :min-width="80">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.tare }}</span>
						<jk-number-input v-else v-model="scope.row.tare" disabled size="mini" placeholder="总皮重(kg)" @input="blurTare(scope.row.tare, scope.rowIndex)" />
					</template>
				</vxe-column>
				<!--				<vxe-column title="厂批" align="left" field="workshopBatchCode" :min-width="220">-->
				<!--					<template slot-scope="scope">-->
				<!--						<span v-if="pageType === 'detail'">{{ scope.row.workshopBatchCode }}</span>-->
				<!--						<div v-else style="display: flex">-->
				<!--							<remote-search-product-input-->
				<!--								:is-valid-date="true"-->
				<!--								placeholder="厂批"-->
				<!--								only-key="workshopBatchId"-->
				<!--								query-name="workshopBatchCode"-->
				<!--								size="mini"-->
				<!--								:form-data="scope.row"-->
				<!--								@on-select="onSelectBatchChange($event, scope.rowIndex)"-->
				<!--							></remote-search-product-input>-->
				<!--							<jk-button v-if="pageType === 'add'" :disabled="!scope.row.productCode" icon="el-icon-plus" size="mini" @click="addChangPi(scope.row)"></jk-button>-->
				<!--						</div>-->
				<!--					</template>-->
				<!--				</vxe-column>-->
				<vxe-column title="毛重(吨)" align="right" field="grossWeight" :min-width="80">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.grossWeight }}</span>
						<jk-number-input v-else v-model="scope.row.grossWeight" size="mini" placeholder="毛重" @change="blurGrossWeight(scope.row.grossWeight, scope.rowIndex)" />
					</template>
				</vxe-column>
				<vxe-column title="件数" align="right" field="num" :min-width="80">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.num }}</span>
						<jk-number-input v-else v-model="scope.row.num" size="mini" placeholder="件数" @change="blurNum(scope.row.num, scope.rowIndex)" />
					</template>
				</vxe-column>
				<vxe-column title="净重(吨)" align="right" field="netWeight" :min-width="80">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.netWeight }}</span>
						<el-input v-else v-model="scope.row.netWeight" disabled size="mini" placeholder="净重" />
					</template>
				</vxe-column>
				<vxe-column title="备注" align="left" field="remark" :min-width="90">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.remark }}</span>
						<el-input v-else v-model="scope.row.remark" type="textarea" :rows="1" size="mini" placeholder="备注" />
					</template>
				</vxe-column>
				<!--				<vxe-column title="记录人" align="left" field="recordName" :min-width="45"></vxe-column>-->
			</jk-table>
		</el-form>
		<remoteSearchCheckboxInputInput
			:dialog-state-disabled="saveDialogStateDisabled.code"
			:primary-batch-code="primaryBatchCode"
			:dialog-state="saveDialogState"
			:check-data-arr="ruleForm.itemList"
			check-key-name="arrivedGoodsItemCode"
			@on-visible-change="onVisibleCheckBoxChange"
			@on-confirm="onFinish"
		>
		</remoteSearchCheckboxInputInput>
	</jk-dialog>
</template>

<script>
    import calHeight from '../../../../mixins/cal-dialog-height';
    import { pageConfig, formatMonth, formatDate, tipsBar } from '/src/utils/jk/jk-tool';
    import remoteSearchProductInput from './components/remote-search-product-input/index.vue';
    import remoteSearchEnterpriseInput from './components/remote-search-enterprise-input/index.vue';
    import remoteSearchTransportInput from './components/remote-search-transport-input/index.vue';
    import remoteSearchCodeInput from './components/remote-search-code-input/index.vue';
    import remoteSearchCheckboxInputInput from './components/remote-search-checkbox-input/index.vue';
    import getMenuColumn from '../../../../mixins/getMenuColumn';
    import {
        productionWeighingRecordTwoGetOneTare,
        productionWeighingRecordTwoParentCreate, productionWeighingRecordTwoParentGet,
        productionWeighingRecordTwoParentUpdate
    } from '../../../../api/production/rawCotton';
    import remoteSearchEmpInput from '@/views/production/order/components/remote-search-emp-input/index.vue';
    import remoteSearchVarietyInput
        from '@/views/putInWarehouse/rawCotton/weighingOrder/components/remote-search-variety-input/index.vue';
    import radioSelectNoticeOrderDialog from '../../package/packageReport/components/radio-select-notice-dialog.vue';
    import checkboxMachineDialog from '../../../machine/qingHuaLine/components/checkbox-machine-dialog.vue';
    import permissionMixin from '../../../../mixins/permission-mixin';
    import XEUtils from 'xe-utils';
    import math from 'dat.gui/src/dat/color/math';
    import { mathJsAdd } from '../../../../utils/jk/jk-cals';

    export default {
        mixins: [calHeight, permissionMixin],
        components: { checkboxMachineDialog,
                      radioSelectNoticeOrderDialog, remoteSearchCodeInput, remoteSearchCheckboxInputInput,
                      remoteSearchVarietyInput, remoteSearchProductInput, remoteSearchEmpInput,
                      remoteSearchEnterpriseInput, remoteSearchTransportInput, getMenuColumn },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                noCalKey: ['oneTare', 'grossWeight', 'num'],
                saveBtnLoading: false,
                showDialog: false,
                saveDialogState: false,
                showLoading: true,
                saveDialogStateDisabled: {},
                primaryBatchCode: '',
                ruleForm: {
                    'auditState': 0,
                    'belongDate': '',
                    'carCode': '',
                    'code': '',
                    'itemList': [],
                    'primaryBatchCode': '',
                    'primaryBatchId': 0,
                    'serviceState': 0,
                    'productCode': '',
                    'productId': 0,
                    'productName': '',
                    'remark': '',
                    'workshopBatchCode': '',
                    'workshopBatchId': 0
                },
                weighingRecordTwo: null,
                prefix: 'production:weighingRecordTwo',
                blurNetWeightNum: null,
                tareState: 0,
                arrivedGoodsItem: {},
                rules: {
                    productCode: [{ required: true, trigger: 'change' }],
                    workshopBatchCode: [{ required: true, trigger: 'change' }],
                    primaryBatchCode: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            /** 导出按钮操作 */
            onReportBtn() {
                return productionWeighingRecordTwoParentGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                            import('@/vendor/Export2Excel').then(excel => {
                                const tHeader = ['厂批', '到货日期', '供应商', '存货编码', '存货名称', '原批', '毛重(T)', '件数', '车号', '单个皮重(kg)', '皮重(kg)', '净重(T)', '运输单位', '付款单位', '品名'];
                                const filterVal = ['workshopBatchCode', 'belongDate', 'supplyName', 'productCode', 'productName', 'primaryBatchCode', 'grossWeight', 'num', 'carCode', 'oneTare', 'tare', 'netWeight', 'transportName', 'payment', 'arriveRemark'];
                                res.data.res ? res.data.res.itemList.forEach(item => {
                                        item.productCode = res.data.res.productCode;
                                        item.productName = res.data.res.productName;
                                        item.workshopBatchCode = res.data.res.workshopBatchCode;
                                        item.primaryBatchCode = res.data.res.primaryBatchCode;
                                }) : [];
                                const list = JSON.parse(JSON.stringify(res.data.res.itemList));
                                const totalItem = {};
                                filterVal.forEach((x, idx) => {
                                    totalItem[x] = this.$refs.jkTable.$refs.xTable.getTableData().footerData[0][idx];
                                });
                                const numArr = [];
                                const weightArr = [];
                                this.ruleForm.itemList.forEach(x => {
                                    x.valueTare = x.oneTare * x.num;
                                    x.valueWeight = x.grossWeight + 0;
                                    numArr.push(x.valueTare);
                                    weightArr.push(x.valueWeight);
                                });
                                var sum = numArr.reduce(function(a, b) {
                                    return a + b;
                                }, 0);
                                var weight = weightArr.reduce(function(a, b) {
                                    return a + b;
                                }, 0);
                                const tare = Math.round(sum);
                                const totalWeight = Number((((weight * 1000) - sum) / 1000).toFixed(3));
                                const data = list.map(v => filterVal.map(j => {
                                    return v[j];
                                }));
                                data.push([totalItem.workshopBatchCode, '-', '-', '-', '-', '-',
                                    totalItem.num, totalItem.grossWeight, '-', totalItem.productCode, tare, totalWeight, '-', '-', '-'
                                ]);
                                excel.export_json_to_excel({
                                    header: tHeader,
                                    data,
                                    filename: `${this.$route.meta.title}`,
                                    autoWidth: true,
                                    bookType: 'xlsx'
                                });
                            });
                    }
                });
            },
            async onFinish(e) {
                this.arrivedGoodsItem = e;
                await this.getWeighingRecordTwo(e[0].primaryBatchCode);
                if (this.ruleForm.primaryBatchCode === this.arrivedGoodsItem[0].primaryBatchCode) {
                    e.length ? e.forEach((e, index) => {
                        this.ruleForm.itemList.push(
                            {
                                'arrivedGoodsItemCode': e && e.code ? e.code : '',
                                'arrivedGoodsItemId': e && e.id ? e.id : 0,
                                'auditState': 0,
                                'belongDate': formatDate(Date.now()),
                                'carCode': e && e.carCode ? e.carCode : '',
                                'code': '',
                                'grossWeight': 0,
                                'netWeight': 0,
                                'num': e && e.residueNum ? e.residueNum : 0,
                                'oneTare': this.weighingRecordTwo || 0,
                                'primaryBatchCode': e && e.primaryBatchCode ? e.primaryBatchCode : 0,
                                'primaryBatchId': 0,
                                'productCode': '',
                                'productId': 0,
                                'productName': '',
                                'recordId': this.$store.state.user.empInfo.id ? this.$store.state.user.empInfo.id : 0,
                                'recordName': this.$store.state.user.empInfo.name ? this.$store.state.user.empInfo.name : '',
                                'remark': '',
                                'tare': 0,
                                'workshopBatchCode': '',
                                'workshopBatchId': 0
                            }
                        );
                    }) : 0;
                } else {
                    this.ruleForm.itemList = [];
                    this.$set(this.ruleForm, 'workshopBatchCode', '');
                    this.$set(this.ruleForm, 'workshopBatchId', null);
                    e.length ? e.forEach((e, index) => {
                        this.ruleForm.itemList.push(
                            {
                                'arrivedGoodsItemCode': e && e.code ? e.code : '',
                                'arrivedGoodsItemId': e && e.id ? e.id : 0,
                                'auditState': 0,
                                'belongDate': formatDate(Date.now()),
                                'carCode': e && e.carCode ? e.carCode : '',
                                'code': '',
                                'grossWeight': 0,
                                'netWeight': 0,
                                'num': e && e.residueNum ? e.residueNum : 0,
                                'oneTare': this.weighingRecordTwo || 0,
                                'primaryBatchCode': e && e.primaryBatchCode ? e.primaryBatchCode : 0,
                                'primaryBatchId': 0,
                                'productCode': '',
                                'productId': 0,
                                'productName': '',
                                'recordId': this.$store.state.user.empInfo.id ? this.$store.state.user.empInfo.id : 0,
                                'recordName': this.$store.state.user.empInfo.name ? this.$store.state.user.empInfo.name : '',
                                'remark': '',
                                'tare': 0,
                                'workshopBatchCode': '',
                                'workshopBatchId': 0
                            }
                        );
                    }) : 0;
                }
                this.$set(this.ruleForm, 'primaryBatchCode', e[0].primaryBatchCode);
                this.$set(this.ruleForm, 'primaryBatchId', e[0].primaryBatchId);
                this.$set(this.ruleForm, 'productCode', this.saveDialogStateDisabled.code);
                this.$set(this.ruleForm, 'productId', this.saveDialogStateDisabled.id);
                this.$set(this.ruleForm, 'productName', this.saveDialogStateDisabled.name);
                this.saveDialogState = false;
            },
            getWeighingRecordTwo(e) {
                return productionWeighingRecordTwoGetOneTare({ batchCode: e }).then(res => {
                    if (res.data.status === 200) {
                        this.weighingRecordTwo = res.data.res || null;
                    }
                });
            },
            // addChangPi(e) {
            //     const lastIndex = this.ruleForm.createList.reduce((acc, curr, idx) => {
            //         if (curr.primaryBatchCode === e.primaryBatchCode) {
            //             return idx;
            //         }
            //         return acc;
            //     }, -1);
            //     this.ruleForm.createList.splice(
            //         lastIndex,
            //         0,
            //         {
            //             'arrivedGoodsItemCode': e.arrivedGoodsItemCode,
            //             'arrivedGoodsItemId': e.arrivedGoodsItemId,
            //             'auditState': 0,
            //             'belongDate': formatDate(Date.now()),
            //             'carCode': e.carCode,
            //             'code': '',
            //             'grossWeight': 0,
            //             'netWeight': null,
            //             'oneTare': 0,
            //             'num': 0,
            //             'primaryBatchCode': e.primaryBatchCode,
            //             'primaryBatchId': 0,
            //             'productCode': e.productCode,
            //             'productId': e.productId,
            //             'productName': e.productName,
            //             'recordId': this.$store.state.user.empInfo.id ? this.$store.state.user.empInfo.id : 0,
            //             'recordName': this.$store.state.user.empInfo.name ? this.$store.state.user.empInfo.name : '',
            //             'remark': '',
            //             'tare': e.tare,
            //             'workshopBatchCode': '',
            //             'workshopBatchId': 0
            //         }
            //     );
            // },
            onSelectProductCodeChange(item) {
                this.saveDialogState = true;
                this.saveDialogStateDisabled = item;
            },
            addTareState() {
                this.tareState = 1;
            },
            addProductList() {
                this.saveDialogState = true;
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const fields = ['primaryBatchCode', 'productCode', 'name3'];
                const cellValue = row[column.field];
                if (cellValue && fields.includes(column.field)) {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow[column.field] === cellValue) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow[column.field] === cellValue) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            footerMethod({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return `合计`;
                        }
                        if (columnIndex === 4) {
                            const numArr = [];
                            this.ruleForm.itemList.forEach(x => {
                                x.valueTare = x.oneTare * x.num;
                                numArr.push(x.valueTare);
                            });
                            var sum = numArr.reduce(function(a, b) {
                                return a + b;
                            }, 0);
                            const tare = Math.round(sum);
                            return tare;
                        }
                        if (columnIndex === 7) {
                            const tareArr = [];
                            const weightArr = [];
                            this.ruleForm.itemList.forEach(x => {
                                x.valueTare = x.oneTare * x.num;
                                x.valueWeigh = x.grossWeight + 0;
                                tareArr.push(x.valueTare);
                                weightArr.push(x.valueWeigh);
                            });
                            var tare = tareArr.reduce(function(a, b) {
                                return a + b;
                            }, 0);
                            var weight = weightArr.reduce(function(a, b) {
                                return a + b;
                            }, 0);
                            const num = ((weight * 1000) - tare) / 1000;
                            const netWeight = Number(num.toFixed(3));
                            return netWeight;
                        }
                        if (this.noCalKey.includes(column.property)) {
                            return XEUtils.sum(data, column.property);
                            // return this.calVal(data, column.property);
                        }
                        return null;
                    })
                ];
            },
            calVal(data, key) {
                let val = 0;
                data.forEach(x => {
                    // if (x[key] === 'tare') {
                    // }
                    val = mathJsAdd(val, x[key]);
                });
                val = val.toFixed(3);
                val = Number(val);
                return val;
            },
            blurTare(event, index) {
                if (this.pageType === 'edit') {
                    this.$set(this.ruleForm.itemList[index], 'netWeight', parseFloat((((this.ruleForm.itemList[index].grossWeight * 1000) - event) / 1000).toFixed(3)));
                }
            },
            blurNetWeight(item, event, index) {
                this.blurNetWeightNum = event;
                this.ruleForm.itemList.forEach(x => {
                    x.oneTare = this.blurNetWeightNum;
                    x.tare = Math.round(this.blurNetWeightNum * x.num);
                    x.netWeight = parseFloat(((x.grossWeight * 1000 - x.tare) / 1000).toFixed(3));
                });
                const $table = this.$refs.jkTable.$refs.xTable;
                $table.updateFooter();
            },
            blurNum(num, index) {
                this.$set(this.ruleForm.itemList[index], 'tare', Math.round(this.ruleForm.itemList[index].oneTare * num));
                const $table = this.$refs.jkTable.$refs.xTable;
                $table.updateFooter();
            },
            blurGrossWeight(event, index) {
                if (this.pageType === 'edit') {
                    this.$set(this.ruleForm.itemList[index], 'netWeight', parseFloat((((event * 1000) - this.ruleForm.itemList[index].tare) / 1000).toFixed(3)));
                }
                const $table = this.$refs.jkTable.$refs.xTable;
                $table.updateFooter();
            },
            onSelectBatchChange(e) {
                this.$set(this.ruleForm, 'workshopBatchCode', e.batchCode);
                this.$set(this.ruleForm, 'workshopBatchId', e.id);
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                return params;
            },
            // 确定
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? productionWeighingRecordTwoParentCreate : productionWeighingRecordTwoParentUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleCheckBoxChange(e) {
                this.saveDialogState = e;
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data.call(this));
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                this.ruleForm.itemList = [];
                return productionWeighingRecordTwoParentGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res || {};
                        this.primaryBatchCode = res.data.res.primaryBatchCode || '';
                        this.saveDialogStateDisabled = {
                            'code': res.data.res.productCode
                        };
                        this.arrivedGoodsItem = {
                            'code': res.data.res.itemList[0].arrivedGoodsItemCode || '',
                            'id': res.data.res.itemList[0].arrivedGoodsItemId || null
                        };
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.ruleForm.itemList.forEach(x => {
                    x.recordName = this.$store.state.user.empInfo.name;
                    x.recordId = this.$store.state.user.empInfo.id;
                    x.belongDate = formatDate(Date.now());
                });
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    // this.$nextTick(() => {
                    //     this.$refs.ruleForm.clearValidate();
                    // });
                    this.getDependentData();
                }
            }
        }
    };
</script>
